package com.yonyou.pmclouds.procedure.processor;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.procedure.entity.ProcedureVO;
import com.yonyou.pmclouds.procedure.mapper.ProcedureMapper;
import org.apache.commons.lang3.StringUtils;

public class ProcedureExtendCodeCheck implements SingleProcessor<ProcedureVO> {
    private ProcedureMapper mapper;
    public ProcedureExtendCodeCheck(ProcedureMapper mapper){
        this.mapper=mapper;
    }
    @Override
    public void process(ProcedureVO vo, ProcedureVO orig) throws BusinessException {
        //首先，判断scode和sname是否已经存在
        if (vo.getPkParent() == null && vo.getPkRoot() == null) {
            //确定为一级类别，则查询一级类别下的所有对象
            ProcedureVO[] procedureVOS = mapper.queryFirstCategory(vo.getPkTenant());//
            check(vo,procedureVOS);
            //将根类型ID设置为一级类别本身ID
            vo.setPkRoot(vo.getPkProcedure());
        } else {
            if (StringUtils.isEmpty(vo.getPkRoot())){
                ProcedureVO parent = mapper.getById(vo.getPkParent());
                if (parent!=null){
                    vo.setPkRoot(parent.getPkRoot());
                }
            }
            ProcedureVO[] procedureVOS = mapper.queryRepetition(vo.getPkParent(), vo.getPkRoot(), vo.getPkTenant());
            check(vo,procedureVOS);
        }
    }
    private void check(ProcedureVO vo,ProcedureVO[] procedureVOS) throws BusinessException {
        if (procedureVOS != null) {
            for (ProcedureVO procedureVO : procedureVOS) {
                if (StringUtils.isNotEmpty(vo.getPkProcedure())&&vo.getPkProcedure().equals(procedureVO.getPkProcedure())){
                    continue;
                }
                if (vo.getSname().equals(procedureVO.getSname()) && vo.getScode().equals(procedureVO.getScode())) {
                    throw new BusinessException("编号和名称都已存在");
                } else if (vo.getSname().equals(procedureVO.getSname())) {
                    throw new BusinessException("名称已存在");
                } else if (vo.getScode().equals(procedureVO.getScode())) {
                    throw new BusinessException("编号已存在");
                }
            }
        }
    }


}
